package com.sweet.logging.logger;

import com.sweet.logging.appender.Appender;

import java.util.List;

/**
 * SweetLogger 的默认实现
 *
 * @author xiexiaofeng
 * @version 1.0     2017年09月08日  11点00分
 */
public class DefaultSweetLogger implements SweetLogger
{
    private String name;
    private int    level; // 日志输出输出级别

    private List<Appender> appenders;

    DefaultSweetLogger(int level)
    {
        this.level = level;
        this.name = "ROOT";
    }

    DefaultSweetLogger(int level, String name, List<Appender> appenders)
    {
        this.level = level;
        this.name = name;
        this.appenders = appenders;
    }

    @Override
    public boolean enable(LoggingLevel loggingLevel)
    {
        return loggingLevel.getCode() >= level;
    }

    @Override
    public void trace(String s)
    {
        append(LoggingLevel.TRACE, s);
    }

    public void debug(String s)
    {
        append(LoggingLevel.DEBUG, s);
    }

    public void info(String s)
    {
        append(LoggingLevel.INFO, s);
    }

    @Override
    public void trace(String s, Throwable throwable)
    {
        append(LoggingLevel.INFO, s, throwable);
    }

    @Override
    public void debug(String s, Throwable throwable)
    {
        append(LoggingLevel.DEBUG, s, throwable);
    }

    @Override
    public void info(String s, Throwable throwable)
    {
        append(LoggingLevel.INFO, s, throwable);
    }

    @Override
    public void warn(String s)
    {
        append(LoggingLevel.WARN, s);
    }

    @Override
    public void warn(String s, Throwable throwable)
    {
        append(LoggingLevel.WARN, s, throwable);
    }

    @Override
    public void error(String s)
    {
        append(LoggingLevel.ERROR, s);
    }

    @Override
    public void error(String s, Throwable throwable)
    {
        append(LoggingLevel.ERROR, s, throwable);
    }

    private void append(LoggingLevel loggingLevel, String message)
    {
        append(loggingLevel, message, null);
    }

    private void append(LoggingLevel loggingLevel, String message, Throwable throwable)
    {
        LoggingEvent event = new LoggingEvent(name, loggingLevel, message, throwable);
        for (Appender appender : appenders)
        {
            appender.write(event);
        }
    }
}
